var grades = new Array();
var sectionCategories = ko.observableArray();
var isSectionsLoaded = false;
var isEventsLoaded = false;
var filterGradeList = new Array();
var tempFilterGradeList = new Array();
var eventViewModel;
var myEventsModel;

var sectionsViewModel = function() {
	var self = this;

	//	self.aypId = ko.observable("");
	self.sections = ko.observableArray();
	self.deleteSectionHandler = function() {

		var deleteSectiondialog = jQuery("#dialog-confirm1").dialog("open");
		deleteSectiondialog.dialog("option", "position", "center");

		ko.dataFor(document.getElementById("dialog-confirm1")).currentItem(this);
		ko.dataFor(document.getElementById("dialog-confirm1")).parentItem(self);
		ko.dataFor(document.getElementById("dialog-confirm1")).type("section");
		ko.dataFor(document.getElementById("dialog-confirm1")).confirmationText("Will delete corresponding events too with sections, Confirm..!!");
	}

	postbox.subscribe(function(newValue) {

		var hasPresent = false;
		console.log("------> postcast");
		console.log(newValue);
		//self.sections.push(newValue)
		var mapping = {
			'ignore' : ["gradesList", "noOfDivisionsList", "namingConvList", "selectedGrade", "noOfDivisions", "namingConvention", "namingConventionChange", "divisionAlphaTitle", "divisionCustTitle", "namingConvention", "isChanged", "divisionsComputed"]
		}

		var jsonData = ko.mapping.toJSON(newValue, mapping);
		var data = ko.mapping.toJSON(newValue);
		var viewModel = ko.mapping.fromJSON(data);
		console.log("viewModel", viewModel);

		for (var i = 0; i < self.sections().length; i++) {
			console.log(self.sections()[i].sectionId(), viewModel.sectionId());
			if (self.sections()[i].sectionId() == viewModel.sectionId()) {
				console.log("-----> SectionId present");
				hasPresent = true
				break;
			}
		}

		if (hasPresent) {
			self.sections.splice(i, 1);
			self.sections.splice(i, 0, new sectionModel(jsonData, viewModel));

			var viewModel = ko.dataFor(document.getElementById("tabs-3"));
			sectionCategories[i + 1].sectionTitle = newValue.sectionTitle();

			for (var j = 0; j < viewModel.events().length; j++) {
				if (viewModel.events()[j].eventSectionId() == self.sections()[i].sectionId()) {
					console.log("--------> deleting event of deleted section");
					var category = ko.utils.arrayFirst(ko.dataFor(document.getElementById("add-Event")).availableCategories(), function(item) {
						return self.sections()[i].sectionId() === item.sectionId;
					});

					viewModel.events()[j].category(category);
				}
			}

		} else {
			self.sections.push(new sectionModel(jsonData, viewModel));

			obj = new Object();
			obj.sectionId = newValue.sectionId();
			obj.sectionTitle = newValue.sectionTitle();
			sectionCategories.push(obj);
		}

		self.sections.sort(function(item1, item2) {
			console.log(item1, item2);
			if (item1.sectionTitle() > item2.sectionTitle()) {
				return 1;
			} else if (item1.sectionTitle() < item2.sectionTitle()) {
				return -1;
			} else {
				return 0;
			}

		});

		ko.dataFor(document.getElementById("add-Event")).availableCategories(sectionCategories);
		newValue.isChanged("false");

		for (var k = 0; k < newValue.grades().length; k++) {
			filterGradeList.push(newValue.grades()[k].ceGradeId())
		}
		console.log("filter length:", filterGradeList.length);
		ko.dataFor(document.getElementById('create-Section')).OriginalgradesList(grades);

		ko.dataFor(document.getElementById("create-Section")).sectionId("");
		ko.dataFor(document.getElementById("create-Section")).sectionTitle("");
		ko.dataFor(document.getElementById("create-Section")).grades([]);

		var vm = ko.validation.group(ko.dataFor(document.getElementById("create-Section")));
		vm.showAllMessages(false);
		console.log("After addition: ", newValue);

	}, this, "addSection");

}

this.addSectionHandler = function() {
	console.log("------>add section", this);

	var viewModel = ko.dataFor(document.getElementById("create-Section"));
	viewModel.grades.push(new createGradeModel());
	var vm = ko.validation.group(viewModel);
	vm.showAllMessages(false);

	/*	ko.dataFor(document.getElementById("create-Section")).sectionId("");
	ko.dataFor(document.getElementById("create-Section")).sectionTitle("");
	ko.dataFor(document.getElementById("create-Section")).grades([]);
	*/
	//this.sections.push("");
	/*	var str= '{"aypId":"","sectionId":"","sectionTitle":"Test Sample","grades":[{"ceGradeId":"schgrd-bff12298-3b9a-4578-a3cc-78850bb848c7","gradeTitle":"Class 10","divisions":[{"classId":"","divisionTitle":"sun"},{"classId":"","divisionTitle":"moon asddahduiasdia"},{"classId":"","divisionTitle":"sky"}]},{"ceGradeId":"schgrd-bff12298-3b9a-4578-a3cc-78850bb848c7","gradeTitle":"Class 10","divisions":[{"classId":"","divisionTitle":"A"},{"classId":"","divisionTitle":"B"},{"classId":"","divisionTitle":"C"},{"classId":"","divisionTitle":"D"},{"classId":"","divisionTitle":"E"}]}]}';
	 this.sections.push(ko.mapping.fromJSON(str));
	 console.log(this);
	 console.log("0------->");
	 ko.dataFor(document.getElementById("create-Section")).sectionId("");
	 ko.dataFor(document.getElementById("create-Section")).sectionTitle("");
	 ko.dataFor(document.getElementById("create-Section")).grades([]);

	 // ko.dataFor(document.getElementById("add-Event")).sectionId("");
	 */

	console.log(ko.dataFor(document.getElementById("create-Section")));
}
var sectionModel = function(_data, value) {
	if ( typeof (data) === 'undefined')
		data = "";
	var self = this;
	var data = jQuery.parseJSON(_data);
	console.log("value", value);
	console.log(data.grades);
	self.aypId = ko.observable(aypId);
	self.sectionId = ko.observable(data.sectionId);
	self.sectionTitle = ko.observable(data.sectionTitle);
	self.grades = ko.observableArray();
	self.gradeColl = ko.computed(function() {
		var gradeArr = new Array();

		for (var i = 0; i < data.grades.length; i++) {
			gradeArr.push(new gradeModel(data.grades[i]));
		}

		self.grades(gradeArr);
		return gradeArr;

	});
	self.selectedItem = value;

	self.deleteGradeHandler = function() {
		console.log("------>Delete Section", this);
		console.log("self----->", self);

		var deleteGradedialog = jQuery("#dialog-confirm1").dialog("open");
		deleteGradedialog.dialog("option", "position", "center");

		ko.dataFor(document.getElementById("dialog-confirm1")).currentItem(this);
		ko.dataFor(document.getElementById("dialog-confirm1")).parentItem(self);
		ko.dataFor(document.getElementById("dialog-confirm1")).type("grade");

		//self.grades().remove(this);
		//	ko.utils.arrayRemoveItem(, this)
		//jQueryparent.grades.remove(this);
		//	jQuery( "#dialog-confirm1" ).dialog( "open" );

	}

	self.grades.sort(function(item1, item2) {
		console.log(item1, item2);
		if (item1.orderNo() > item2.orderNo()) {
			return 1;
		} else if (item1.orderNo() < item2.orderNo()) {
			return -1;
		} else {
			return 0;
		}

	});
}
var gradeModel = function(data) {
	var self = this;
	console.log("---------> Grade Model");
	self.ceGradeId = ko.observable(data.ceGradeId);
	self.gradeTitle = ko.observable(data.gradeTitle);
	self.orderNo = ko.observable(data.orderNo);
	self.divisions = ko.computed(function() {
		var divArr = new Array();

		for (var i = 0; i < data.divisions.length; i++) {
			divArr.push(new divisionModel(data.divisions[i]));
		}

		return divArr;
	});
}
var divisionModel = function(data) {
	var self = this;

	self.classId = ko.observable(data.classId);
	self.divisionTitle = ko.observable(data.divisionTitle);

}
var createSectionViewModel = function() {
	var self = this;

	//self.aypId = ko.observable("acad-60bf7bdf-6ef2-456e-a981-e00be80ba260");
	self.aypId = ko.observable(aypId);
	self.sectionId = ko.observable("");
	self.sectionTitle = ko.observable("").extend({
		required : true
	});
	self.grades = ko.observableArray().extend({
		required : true
	});
	self.OriginalgradesList = ko.observableArray(grades);
	self.noOfDivisionsList = ko.observableArray(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]);
	self.namingConvList = ko.observableArray(["Alphabetical", "Custom"]);
	self.isChanged = ko.observable("false");

	self.gradesList = ko.computed(function() {
		console.log("Collectiong gradelist", self.OriginalgradesList().length);
		return ko.utils.arrayFilter(self.OriginalgradesList(), function(item) {
			console.log("--->", item);

			var rtnVal = true;
			for (var i = 0; i < filterGradeList.length; i++) {
				if ((item.ceGradeId == filterGradeList[i])) {
					rtnVal = false;
				}
			}
			return rtnVal;
		});
	});
	self.isChanged.subscribe(function(newValue) {
		if (self.isChanged() == "true") {
			console.log("->", self);
			postbox.notifySubscribers(self, "addSection");
		}
	});

	self.removeGrade = function(item) {
		console.log("removing grade", item);
		console.log("Self", self);
		//var self = this;

		var removeGradedialog = jQuery("#dialog-confirm1").dialog("open");
		removeGradedialog.dialog("option", "position", "center");

		ko.dataFor(document.getElementById("dialog-confirm1")).currentItem(item);
		ko.dataFor(document.getElementById("dialog-confirm1")).parentItem(self);
		ko.dataFor(document.getElementById("dialog-confirm1")).type("grade");
		//self.grades.remove(item);
	}

	self.gradeSorting = ko.computed(function() {
		ko.utils.arrayForEach(self.grades(), function(item) {
			console.log("item.gradeTitle():", item.gradeTitle());
		});

		self.grades.sort(function(item1, item2) {
			console.log("grade sorting:::", item1, item2);
			if (item1.orderNo() > item2.orderNo()) {
				return 1;
			} else if (item1.orderNo() < item2.orderNo()) {
				return -1;
			} else {
				return 0;
			}

		});
	})
}
var createGradeModel = function() {
	var self = this;

	self.selectedGrade = ko.observable("");
	self.ceGradeId = ko.computed(function() {

		return self.selectedGrade() === undefined ? "" : self.selectedGrade().ceGradeId;
	});
	self.gradeTitle = ko.computed(function() {
		console.log(self.selectedGrade() === undefined ? "" : self.selectedGrade().gradeTitle);
		return self.selectedGrade() === undefined ? "" : self.selectedGrade().gradeTitle;
	});
	self.orderNo = ko.computed(function() {
		console.log(self.selectedGrade() === undefined ? "" : self.selectedGrade().orderNo);
		return self.selectedGrade() === undefined ? "" : self.selectedGrade().orderNo;
	});
	//self.gradeTitle = ko.observable("");
	self.noOfDivisions = ko.observable("");

	self.namingConvention = ko.observable("");
	selectTemplate = function(value) {
		console.log("-------->", self.namingConvention());
		return self.namingConvention() == "Alphabetical" ? "alpha-division-template" : "custom-division-template";
	};
	self.divisions = ko.observableArray();
	self.divisionsComputed = ko.computed(function() {
		var divArr = self.divisions === undefined ? new Array() : self.divisions();
		console.log("----->namingConvention: ", self.namingConvention());
		if (divArr.length < self.noOfDivisions()) {
			for (var i = divArr.length; i < self.noOfDivisions(); i++) {
				console.log("i:" + i);
				if (self.namingConvention() == "Custom") {
					divArr.push(new createDivisionModel("", "", "", "Custom"));
				} else {
					divArr.push(new createDivisionModel("", getAplhabatic(i), "", "Alphabetical"));
				}
			}
		} else {
			var len = divArr.length;
			for (var i = self.noOfDivisions(); i < len; i++) {
				divArr.pop();
			}
		}

		self.divisions(divArr);

		return divArr;
	});

	/*self.selectedGrade = ko.computed({
	 read: function(){
	 var obj = new Object();
	 obj.ceGradeId = self.ceGradeId();
	 obj.gradeTitle = self.gradeTitle();

	 return obj;

	 },
	 write: function(value){
	 if(value != undefined)
	 {
	 console.log("write:  ",value);
	 self.ceGradeId(value.ceGradeId);
	 self.gradeTitle(value.gradeTitle);
	 }

	 }
	 });
	 */
	self.namingConventionChange = ko.computed(function() {

		for (var j = 0; j < self.divisions().length; j++) {
			self.divisions()[j].namingConvention(self.namingConvention());
		}
		return self.namingConvention();
	});
}

ko.observableArray.fn.find = function(prop, data) {
	var valueToMatch = data[prop];
	return ko.utils.arrayFirst(this(), function(item) {
		return item[prop] === valueToMatch;
	});
};

var createDivisionModel = function(_id, _alphTitle, _custTitle, _type) {
	var self = this;

	self.classId = ko.observable(_id);
	self.divisionAlphaTitle = ko.observable(_alphTitle);
	self.divisionCustTitle = ko.observable(_custTitle);
	self.namingConvention = ko.observable(_type);
	self.divisionTitle = ko.computed(function() {
		console.log("self.namingConvention():" + self.namingConvention());
		if (self.namingConvention() == 'Alphabetical') {
			return self.divisionAlphaTitle();
		} else {
			return self.divisionCustTitle();
		}
	});
}

this.addGradeHandler = function() {
	console.log("adding grade", this);
	var self = this;
	self.grades.push(new createGradeModel());

}

this.createSectionHandler = function() {
	console.log("creating sections", this);

	//	var vm1 = ko.validation.group(this.holidays()[0]);

	var duplicateArr = ko.dependentObservable(function() {
		var types = ko.utils.arrayMap(this.grades(), function(item) {
			return item.ceGradeId()
		})
		return ko.utils.arrayGetDistinctValues(types);
	}, this);

	console.log("countArr:", duplicateArr(), duplicateArr().length, this.grades().length);

	if (duplicateArr().length != this.grades().length) {
		jQuery("#errorText").html("Duplicate Grades present");
		jQuery("#dialog-alert").dialog("option", "title", "Error");
		var alertDialog = jQuery("#dialog-alert").dialog("open");
		alertDialog.dialog("option", "position", "center");

		return;
	}

	var vm = ko.validation.group(this);

	if (this.isValid() == false) {
		console.log("thanQ");
		vm.showAllMessages();
		//alert("Please fill all Required fields before saving.");
		//jQuery("#dialog-validationError-alert").dialog("open");

		jQuery("#errorText").html("Error! Some of the required field are not correctly entered. Close this message to view the exact nature of the error.");
		jQuery("#dialog-alert").dialog("option", "title", "Error");

		var alertDialog = jQuery("#dialog-alert").dialog("open");
		alertDialog.dialog("option", "position", "center");

		return;
	}

	showLoader(true, TYPE_SAVING);
	var self = this;
	var mapping = {
		'ignore' : ["gradesList", "noOfDivisionsList", "namingConvList", "selectedGrade", "noOfDivisions", "namingConvention", "namingConventionChange", "divisionAlphaTitle", "divisionCustTitle", "namingConvention", "isChanged", "divisionsComputed", "OriginalgradesList", "errors"]
	}
	var jsonData = ko.mapping.toJSON(this, mapping)
	console.log(jsonData);

	jQuery.ajax({
		data : {
			savedata : jsonData
		},
		url : url + "saveAcademicSection",
		type : "post",
		success : function(result) {
			console.log("------>", result);
			console.log("self------>", self);
			console.log("result.sectionId------>", result.sectionId);
			console.log("------>", result.grades[0].divisions.length);
			jQuery("#create-Section").dialog("close");

			self.sectionId(result.sectionId);

			for (var i = 0; i < result.grades[0].divisions.length; i++) {
				self.grades()[0].divisions()[i].classId(result.grades[0].divisions[i].classId);
			}

			//	self = ko.mapping.fromJSON(result);
			self.isChanged("true");

			showLoader(false);
			console.log(self);
		},
		error : function(jqXHR, textStatus, errorThrown) {
			console.log("error createSectionHandler", jqXHR, textStatus, errorThrown);

			showLoader(false);
			//jQuery("#dialog-error-alert").dialog("open");

			jQuery("#errorText").html("Error! occured while performing Server Operation");
			jQuery("#dialog-alert").dialog("option", "title", "Error");
			var alertDialog = jQuery("#dialog-alert").dialog("open");
			alertDialog.dialog("option", "position", "center");

		}
	});
}

this.editSectionHandler = function() {
	console.log("---------> Editing Section", this);
	var editSectionDialog = jQuery("#create-Section").dialog("open");
	editSectionDialog.dialog("option", "position", "center");

	var obj = this.grades();
	console.log("obj:", obj[0].ceGradeId());
	/* for filter maintaining */
	tempFilterGradeList = new Array();
	for (var l = 0; l < obj.length; l++) {
		for (var k = 0; k < filterGradeList.length; k++) {
			if (filterGradeList[k] == obj[l].ceGradeId()) {
				tempFilterGradeList.push(filterGradeList[k]);
				filterGradeList.splice(k, 1);
				break;
			}
		}
	}
	/* END*/

	console.log("filter length:", filterGradeList.length, tempFilterGradeList.length);
	console.log("Temp filter length:", tempFilterGradeList.length);

	ko.dataFor(document.getElementById('create-Section')).OriginalgradesList(grades);

	for (var i = 0; i < obj.length; i++) {
		var namingConvention = "Alphabetical";
		var gradeModel = new createGradeModel();
		ko.dataFor(document.getElementById("create-Section")).grades.push(gradeModel);
		if (obj[i].divisions()[0].divisionTitle() != "A") {
			namingConvention = "Custom";
		}
		gradeModel.namingConvention(namingConvention);
		gradeModel.noOfDivisions(obj[i].divisions().length);

		var selectedGrade = new Object();
		selectedGrade.ceGradeId = obj[i].ceGradeId();
		selectedGrade.gradeTitle = obj[i].gradeTitle();
		gradeModel.selectedGrade(selectedGrade);

		for (var j = 0; j < obj[i].divisions().length; j++) {

			if (namingConvention == "Custom") {
				gradeModel.divisions()[j].divisionCustTitle(obj[i].divisions()[j].divisionTitle());
				gradeModel.divisions()[j].divisionAlphaTitle(getAplhabatic(j));
			} else {
				gradeModel.divisions()[j].divisionAlphaTitle(obj[i].divisions()[j].divisionTitle());
			}

			gradeModel.divisions()[j].namingConvention(namingConvention);
			gradeModel.divisions()[j].classId(obj[i].divisions()[j].classId());
		}
	}

	console.log("obj------>", obj);
	ko.dataFor(document.getElementById("create-Section")).sectionTitle(this.sectionTitle());
	ko.dataFor(document.getElementById("create-Section")).sectionId(this.sectionId());
	//ko.dataFor(document.getElementById("create-Section")).grades();

	console.log("After-->", ko.dataFor(document.getElementById("create-Section")).grades());
}

this.cancelSectionHandler = function() {
	console.log("Cancel create section", tempFilterGradeList, filterGradeList);

	if (this.sectionId() != "") {
		for (var k = 0; k < tempFilterGradeList.length; k++) {
			filterGradeList.push(tempFilterGradeList[k])
		}
		console.log("filter length:", filterGradeList.length);
		ko.dataFor(document.getElementById('create-Section')).OriginalgradesList(grades);
	}

	this.sectionId("");
	this.sectionTitle("");
	this.grades([]);
}
function getAplhabatic(count) {
	var value = "A";

	if (count == 0) {
		value = "A";
	} else if (count == 1) {
		value = "B";
	} else if (count == 2) {
		value = "C";
	} else if (count == 3) {
		value = "D";
	} else if (count == 4) {
		value = "E";
	} else if (count == 5) {
		value = "F";
	} else if (count == 6) {
		value = "G";
	} else if (count == 7) {
		value = "H";
	} else if (count == 8) {
		value = "I";
	} else if (count == 9) {
		value = "J";
	}

	return value;
}

jQuery(function() {

	$("body").on({
		ajaxStart : function() {
			$(this).addClass("loading");
		},
		ajaxStop : function() {
			$(this).removeClass("loading");
		}
	});
	console.log("--------> DOM loaded for sections");

	init();
	myAcademicYearModel = new createAcademicYearModel();
	//console.log("myAcademicYearModel >> ",myAcademicYearModel);
	ko.applyBindings(myAcademicYearModel, document.getElementById('tabs-1'));
	ko.applyBindings(new deleteConfirmViewModel(), document.getElementById('dialog-confirm1'));

	getSchoolGrades();
	console.log("editEventHolidayOnlyasdas", editEventHolidayOnly());
	if (aypId != "") {
		myEventsModel = new eventsModel();
		ko.applyBindings(new sectionsViewModel(), document.getElementById('tabs-2'));
		ko.applyBindings(new createSectionViewModel(""), document.getElementById('create-Section'));
		ko.applyBindings(myEventsModel, document.getElementById('tabs-3'));
		ko.applyBindings(new addEventViewModel(), document.getElementById('add-Event'));
	} else {
		isSectionsLoaded = true;
		isEventsLoaded = true;
		jQuery("#tabs").tabs("option", "disabled", [1, 2])
	}

	if (aypId != "") {

		console.log("-----a--> loading")
		showLoader(true, TYPE_LOADING);
		getAcademicYearPlan();
		//getSchoolAcademicSections("simple")
	}
	//getSchoolAcademicEvents();
	//getSchoolSections("simple");
	//	ko.applyBindings(new eventsModel(),document.getElementById('tabs-3'));
	//	ko.applyBindings(new addEventViewModel(),document.getElementById('add-Event'));
})

